package com.spring.housing.aspect;

import com.spring.housing.acceptType.PageParams;
import com.spring.housing.constant.Constants;
import com.spring.housing.returnType.CommenResult;
import com.spring.housing.returnType.PageReq;
import com.spring.housing.returnType.PageType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;


@Component
@Slf4j
@Aspect
public class LogImportantDo {
    @Value("${accesstoken}")
    String accesstoken;

    /**
     * 对重要的行为进行记录
     */
    @Pointcut("execution(public * com.spring.housing.controller.page..*.*(..))")
    private void behaviorRecord() {
    }

    @Pointcut("execution(public * com.spring.housing.controller.commen..*.*(..))")
    private void doCommen() {
    }
    @Pointcut("execution(public * com.spring.housing.controller.page.*.*(..))")
    private void pagecontrller() {
    }

    @Around("pagecontrller()")
    public Object test(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = ((MethodSignature) point.getSignature());
        System.out.println("环绕通知的目标方法名：" + signature.getName());


        //获取参数值
        Object [] paranValues = point.getArgs();
        PageParams paranValues1 = (PageParams) paranValues[0];
        Object proceed = null;
        if(paranValues1.getPageReq()==null){
                //给定默认的页面请求参数
            PageReq pageReq = new PageReq();
            pageReq.setPageSize(10);
            pageReq.setPageNo(1);
            paranValues1.setPageReq(pageReq);

        }
        return   point.proceed();
    }

    /*
     *对接口：client端的被拦截的方法重新设置返回值
     */
    @AfterReturning(pointcut = "doCommen()", returning = "response")
    public CommenResult doAfterIntercepter(CommenResult response) throws Exception {
        if (response == null) {
           return new CommenResult(500,"server端无返回信息","null");
        }
        return response;
    }

    //参照openfeign的RequstConfig,把requstHead的值accessToken设置好
    @Before("doCommen()")
    public void setAccessToken() {

        log.info("Service AccessToken{}",accesstoken);
        Constants.ACCESSTOKEN = accesstoken;
    }
}